package utils

import (
	"common/global"
	"github.com/go-redis/redis/v8"
	"time"
)

/*redis相关操作*/

// 获取redis键值对的值
func GetRedisKeyValuePair(key string) (string, error) {
	res, err := global.Client.Get(global.EmptyCtx, key).Result()
	if err != nil {
		return "", err
	}
	return res, nil
}

// 存储redis键值对
func SetRedisKeyValuePair(key string, value interface{}, expire time.Duration) error {
	return global.Client.Set(global.EmptyCtx, key, value, expire).Err()
}

// 获取redis队列的长度
func GetRedisListLen(key string) (int64, error) {
	result, err := global.Client.LLen(global.EmptyCtx, key).Result()
	if err != nil {
		return 0, err
	}
	return result, nil
}

// 设置redis的锁
func SetRedisNx(key string, value string, expire time.Duration) (bool, error) {
	res, err := global.Client.SetNX(global.EmptyCtx, key, value, expire).Result()
	if err != nil {
		return false, err
	}
	return res, nil
}

// redis 队列的存入
func SetRedisList(key string, value interface{}) error {
	return global.Client.LPush(global.EmptyCtx, key, value).Err()
}

// redis  哈希的存入
func SetRedisHash(key string, value ...interface{}) error {
	return global.Client.HSet(global.EmptyCtx, key, value).Err()
}

// 从redis队列取出东西
func TakeOutRedisList(key string) error {
	return global.Client.RPop(global.EmptyCtx, key).Err()
}

// redis自增
func SetRedisIncr(key string) (int64, error) {
	res, err := global.Client.Incr(global.EmptyCtx, key).Result()
	if err != nil {
		return 0, err
	}
	return res, nil
}

// 为某个缓存设置过期时间
func SetRedisExpire(key string, expire time.Duration) {
	global.Client.Expire(global.EmptyCtx, key, expire)
}

// 获取redis自增的值
func GetRedisIncrValue(key string) (int, error) {
	res, err := global.Client.Get(global.EmptyCtx, key).Int()
	if err != nil {
		return 0, err
	}
	return res, nil
}

// 有序集合存入
func SetRedisOrderedSet(key string, z *redis.Z) error {
	return global.Client.ZAdd(global.EmptyCtx, key, z).Err()
}

// 获取有序集合
func GetRedisOrderedSet(key string, start, stop int64) ([]redis.Z, error) {
	res, err := global.Client.ZRangeWithScores(global.EmptyCtx, key, start, stop).Result()
	if err != nil {
		return nil, err
	}
	return res, nil
}

// 删除某个缓存
func DelRedis(key string) error {
	return global.Client.Del(global.EmptyCtx, key).Err()
}

// SetBit 设置位图
func SetBit(key string, offset int64, value int) error {
	return global.Client.SetBit(global.EmptyCtx, key, offset, value).Err()
}

// GetBit 获取位图
func GetBit(key string, offset int64) (int64, error) {
	return global.Client.GetBit(global.EmptyCtx, key, offset).Result()
}

// BitCount 统计位图中1的个数
func BitCount(key string) (int64, error) {
	return global.Client.BitCount(global.EmptyCtx, key, nil).Result()
}

// LRange 获取队列的值
func LRange(key string) ([]string, error) {
	result, err := global.Client.LRange(global.EmptyCtx, key, 0, -1).Result()
	return result, err
}
